#!/usr/bin/env ruby
require 'rubygems'
require 'activerecord'

BASE = ''
ENV = 'production'

dbconfig = YAML::load(File.open(BASE+'config/database.yml'))
ActiveRecord::Base.establish_connection(dbconfig[ENV])
@sql = ActiveRecord::Base.connection();

def set_project_id(parent_id, parent_project_id, title, level)
  #puts title
  if parent_project_id==nil
    puts "=== #{level}: no project_id for #{parent_id}: #{title}"
    return
  end   
  @sql.execute "update tasks set project_id=#{parent_project_id} where task_id=#{parent_id}";
  #puts "setting project_id as #{parent_project_id} for tasks with parent #{parent_id}"
  r = @sql.execute "select id, project_id, title from tasks where task_id=#{parent_id}";
  #puts "level #{level}: #{r.num_rows} children"
  r.each { |parent_id, parent_project_id, title|
    set_project_id(parent_id, parent_project_id, title, level+1)
    }
end

r = @sql.execute "select id, project_id, title from tasks where task_id=0";
r.each { |id, project_id, title|
  set_project_id(id, project_id, title, 0)
  }

